package com.topnav.mc.schedule.job;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.topnav.mc.admin.entity.GbServer;
import com.topnav.mc.admin.entity.bean.EntityOperateLogBean;
import com.topnav.mc.admin.entity.bean.GbServerBean;
import com.topnav.mc.admin.entity.param.EntityOperateLogParam;
import com.topnav.mc.admin.entity.param.GbServerParam;
import com.topnav.mc.admin.service.IEntityOperateLogService;
import com.topnav.mc.admin.service.IGbServerService;
import com.topnav.mc.gbserverapi.GbServerApi;
import com.topnav.mc.lock.SyncLock;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;

/**
 * 更新设备和通道的注册
 * 暂不用
 */
@Component
@Slf4j
@Deprecated
public class SyncGbDeviceChannelJob implements Job, Serializable {
    @Autowired
    private IEntityOperateLogService entityOperateLogService;

    @Autowired
    private IGbServerService gbServerService;
    @Resource
    private GbServerApi api;
    private String host = "http://%s:%s";

    @Override
    @SyncLock(key="SyncGbDeviceChannelJob-LOCK",dueSec = 30*60)
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try{
            this.execute1();
        }catch (JobExecutionException e){
            throw  e;
        }catch (Exception e){
            log.error("******* SyncGbDeviceChannelJob.execute: {}",e.toString());

        }
    }

    public void execute1() throws Exception {
        log.debug(">>>>>> 正在同步设备及状态 ......");

        /** 查询所有的在线国标服务器, 并测试服务器是否在线 */
        List<GbServerBean> gbServerList = gbServerService.listInfo();
        String url=null;
        String result = null;
        GbServerBean gbServerBean=null;
        for(int i=gbServerList.size()-1;i>=0;i--){
            gbServerBean=gbServerList.get(i);
            url = String.format(host,gbServerBean.getHost(),gbServerBean.getApiPort());
            try{
                result = api.login(url,"test","test");
            }catch (Exception e){
                //com.dtflys.forest.exceptions.ForestRuntimeException: java.net.ConnectException: Failed to connect to /159.75.88.24:18080
                if (e.toString().indexOf("Failed to connect to")>-1){
                    log.error(e.toString());
                    this.updateGbServerState(gbServerBean,0);
                    gbServerList.remove(i);
                    continue;
                }
            }
            this.updateGbServerState(gbServerBean,1);
        }

        //查询所有变更的数据
        QueryWrapper<EntityOperateLogParam> devlogWrapper = new QueryWrapper<EntityOperateLogParam>();
        devlogWrapper.eq("state",0);
        List<EntityOperateLogBean> datas = entityOperateLogService.listInfo(devlogWrapper);
        if (CollectionUtils.isEmpty(datas)){
            return;
        }

        JSONObject json = null;
        for(EntityOperateLogBean bean : datas){
            json = JSONObject.parseObject(bean.getData());
            if ("Device".equals(bean.getEntityName())){
                //设备

            }else if ("DeviceChannel".equals(bean.getEntityName())){
                //通道
            }
        }
    }

    /**
     * 更新国标服务器状态
     * @param data
     * @param state  0离线，1在线
     */
    private void updateGbServerState(GbServerBean data,Integer state){
        if ((data.getOnline() == 1 && state==0)||(data.getOnline() == 0 && state==1)){
            data.setOnline(state);
            UpdateWrapper<GbServer> updateWrapper = new UpdateWrapper<GbServer>();
            updateWrapper.set("online",state).eq("id",data.getId());
            gbServerService.update(updateWrapper);
        }
    }


}
